#include "commentwidget.h"
#include "ui_commentwidget.h"

#include <QStandardItemModel>
#include <QSqlQuery>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QDateTime>
#include <QHeaderView>

commentWidget::commentWidget(int userId, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::commentWidget),
    m_userId(userId),
    m_currentProductId(-1)
{
    ui->setupUi(this);
    setWindowTitle("商品评价");
    // 应用全局样式表
        setStyleSheet(R"(
            QDialog {
                background-color: #f5f7fa;
                font-family: 'Segoe UI', 'Microsoft YaHei';
            }

            QGroupBox {
                background-color: white;
                border-radius: 8px;
                border: 1px solid #dcdfe6;
                margin-top: 1.5ex;
                font-weight: bold;
                color: #303133;
                padding-top: 15px;
            }

            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px;
            }

            QTableView, QTextEdit, QComboBox, QRadioButton, QPushButton {
                font-size: 14px;
            }

            QTableView {
                background-color: white;
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                gridline-color: #ebeef5;
                selection-background-color: #ecf5ff;
                selection-color: #303133;
            }

            QTableView::item {
                padding: 8px;
            }

            QHeaderView::section {
                background-color: #f0f2f5;
                padding: 8px;
                border: none;
                font-weight: bold;
            }

            QTextEdit {
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 8px;
            }

            QComboBox {
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 5px 10px;
                min-height: 28px;
            }

            QRadioButton {
                spacing: 5px;
            }

            QPushButton {
                background-color: #409eff;
                color: white;
                border-radius: 4px;
                padding: 8px 16px;
                border: none;
                min-width: 80px;
            }

            QPushButton:hover {
                background-color: #66b1ff;
            }

            QPushButton:pressed {
                background-color: #3a8ee6;
            }

            QPushButton#cancelButton {
                background-color: #f56c6c;
            }

            QPushButton#cancelButton:hover {
                background-color: #f78989;
            }

            QLabel {
                color: #606266;
            }
        )");

    // 初始化商品表格
    m_model = new QStandardItemModel(this);
    m_model->setHorizontalHeaderLabels({"商品ID", "商品名称", "购买次数"});
    ui->productsTableView->setModel(m_model);
    ui->productsTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->productsTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->productsTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 初始化评论表格
    m_commentModel = new QStandardItemModel(this);
    m_commentModel->setHorizontalHeaderLabels({"评论ID", "商品ID","评分", "评论内容", "日期"});
    ui->commentTable->setModel(m_commentModel);
    ui->commentTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->commentTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->commentTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->commentTable->setColumnWidth(0, 60);   // 评论ID列宽
    ui->commentTable->setColumnWidth(1, 60);   // 商品ID
    ui->commentTable->setColumnWidth(2, 60);   // 评分
    ui->commentTable->setColumnWidth(3, 200);  // 评论内容
    ui->commentTable->setColumnWidth(4, 160);  // 创建时间
    ui->commentTable->horizontalHeader()->setStretchLastSection(true);

    // 设置评分下拉框
    ui->ratingComboBox->addItem("1星", 1);
    ui->ratingComboBox->addItem("2星", 2);
    ui->ratingComboBox->addItem("3星", 3);
    ui->ratingComboBox->addItem("4星", 4);
    ui->ratingComboBox->addItem("5星", 5);
    ui->ratingComboBox->setCurrentIndex(4);

    //设置日期下拉框
    QString today="今天";
    QString week="本周";
    QString month="本月";
    QString all="全部";

    ui->DateBox->addItem("今天",today);
    ui->DateBox->addItem("本周",week);
    ui->DateBox->addItem("本月",month);
    ui->DateBox->addItem("全部",all);
    ui->DateBox->setCurrentIndex(3);

    // 初始化筛选下拉框
    loadProductsToCombo();

    // 默认选中全部评分
    ui->ratingAll->setChecked(true);

    // 初始时禁用评价区域和回复区域
    ui->commentGroupBox->setEnabled(false);
    ui->commentTextEdit->setEnabled(false);

    // 初始化回复区域状态（无评论时禁用）
        ui->replyTextEdit->setEnabled(false);  // 初始禁用

    // 加载用户购买过的商品
    loadPurchasedProducts();

    // 连接信号与槽
   connect(ui->commentTable, &QTableView::clicked, this, &commentWidget::on_commentTable_clicked);

    // 连接筛选按钮
//    connect(ui->productCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &commentWidget::filterComments);
   connect(ui->productCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [this](int index) {
           Q_UNUSED(index); // 忽略参数
           filterComments();
       });
//   connect(ui->rating5, &QRadioButton::toggled, this, &commentWidget::filterComments);
//    connect(ui->rating4, &QRadioButton::toggled, this, &commentWidget::filterComments);
//    connect(ui->rating3, &QRadioButton::toggled, this, &commentWidget::filterComments);
//    connect(ui->rating2, &QRadioButton::toggled, this, &commentWidget::filterComments);
//    connect(ui->rating1, &QRadioButton::toggled, this, &commentWidget::filterComments);
//    connect(ui->DateBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &commentWidget::filterComments);
    connect(ui->resetButton, &QPushButton::clicked, this, &commentWidget::on_resetButton_clicked);

   connect(ui->rating5, &QRadioButton::toggled, [this](bool checked) {
           Q_UNUSED(checked); // 忽略参数
           filterComments();
       });

       connect(ui->rating4, &QRadioButton::toggled, [this](bool checked) {
           Q_UNUSED(checked);
           filterComments();
       });

       connect(ui->rating3, &QRadioButton::toggled, [this](bool checked) {
           Q_UNUSED(checked);
           filterComments();
       });

       connect(ui->rating2, &QRadioButton::toggled, [this](bool checked) {
           Q_UNUSED(checked);
           filterComments();
       });

       connect(ui->rating1, &QRadioButton::toggled, [this](bool checked) {
           Q_UNUSED(checked);
           filterComments();
       });

       connect(ui->DateBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [this](int index) {
           Q_UNUSED(index);
           filterComments();
       });

    //初始加载所有评论
    filterComments();
}

commentWidget::~commentWidget()
{
    delete ui;
}

 //加载购买商品
void commentWidget::loadPurchasedProducts()
{
    // 清空现有数据
    m_model->removeRows(0, m_model->rowCount());

    // 查询购买过的商品
    QSqlQuery query;
    query.prepare(
                "SELECT p.product_id,p.name,COUNT(oi.order_detail_id) as purchase_count "
                "FROM OrderDetails oi "
                "JOIN Orders o ON oi.order_id=o.order_id "
                "JOIN products p ON oi.product_id=p.product_id "
                "WHERE o.user_id=:user_id "
                "GROUP BY p.product_id,p.name"
      );
    query.bindValue(":user_id", m_userId);

    if(query.exec()){
        while(query.next()){
            int productId=query.value("product_id").toInt();
            QString name=query.value("name").toString();
            int count=query.value("purchase_count").toInt();
            QList<QStandardItem*> row;
            row<<new QStandardItem(QString::number(productId));
            row<<new QStandardItem(name);
            row<<new QStandardItem(QString::number(count));
            m_model->appendRow(row);
        }
    }else{
        qWarning() << "Failed to load purchased products:" << query.lastError().text();
        QMessageBox::critical(this, "错误", "加载购买商品失败");
    }

}

   //加载商品到筛选下拉框
void commentWidget::loadProductsToCombo()
{
    // 清空现有数据
    ui->productCombo->clear();
    ui->productCombo->addItem("所有商品", -1);

    // 查询所有商品
    QSqlQuery query;
    query.prepare("SELECT product_id, name FROM products");

    if(query.exec()){
        while(query.next()){
            int productId=query.value("product_id").toInt();
            QString name=query.value("name").toString();
            ui->productCombo->addItem(name, productId);
        }
    }else{
        qWarning() << "Failed to load products:" << query.lastError().text();
    }
}

//提交评论
void commentWidget::on_commentButton_clicked()
{
    if (m_currentProductId == -1) {
            QMessageBox::warning(this, "提交失败", "请先选择一个商品");
            return;
        }

        QString comment = ui->commentTextEdit->toPlainText().trimmed();
        if (comment.isEmpty()) {
            QMessageBox::warning(this, "提交失败", "评价内容不能为空");
            return;
        }

        int rating = ui->ratingComboBox->currentData().toInt();

        // 查找最近一次购买该商品的订单
        QSqlQuery query;
        query.prepare(
            "SELECT o.order_id "
            "FROM Orders o "
            "JOIN OrderDetails oi ON o.order_id = oi.order_id "
            "WHERE o.user_id = :user_id AND oi.product_id = :product_id "
            "ORDER BY o.create_time DESC "
            "LIMIT 1"
        );
        query.bindValue(":user_id", m_userId);
        query.bindValue(":product_id", m_currentProductId);

        int orderId = -1;
        if (query.exec() && query.next()) {
            orderId = query.value("order_id").toInt();
        } else {
            QMessageBox::critical(this, "错误", "无法找到相关订单");
            return;
        }

        // 插入评价到数据库
        query.prepare(
            "INSERT INTO Comments (user_id, product_id, order_id, rating, content, create_time) "
            "VALUES (:user_id, :product_id, :order_id, :rating, :content, :create_time)"
        );
        query.bindValue(":user_id", m_userId);
        query.bindValue(":product_id", m_currentProductId);
        query.bindValue(":order_id", orderId);
        query.bindValue(":rating", rating);
        query.bindValue(":content", comment);
        query.bindValue(":create_time", QDateTime::currentDateTime());

        qDebug() << "Inserting comment with values:"
                     << "User ID:" << m_userId
                     << "Product ID:" << m_currentProductId
                     << "Order ID:" << orderId
                     << "Rating:" << rating
                     << "Content:" << comment.left(30) + "..." ;

        if (query.exec()) {
            QMessageBox::information(this, "成功", "评价已提交！");
            ui->commentTextEdit->clear();
            ui->commentGroupBox->setEnabled(false);
            m_currentProductId = -1;

            // 刷新评论列表
            loadProductComments(m_currentProductId);
        } else {
            QString error = "评价提交失败: " + query.lastError().text();
            qCritical() << error;
            QMessageBox::critical(this, "提交失败", error);
    }
}

//取消按钮
void commentWidget::on_cancelButton_clicked()
{
    this->close();
}

//选择商品后加载评论
void commentWidget::on_productsTableView_clicked(const QModelIndex &index)
{
    if(!index.isValid())     return;
    int row = index.row();
    QModelIndex idIndex=m_model->index(row,0);
    m_currentProductId=m_model->data(idIndex).toInt();

    // 启用评价区域
       ui->commentGroupBox->setEnabled(true);
       ui->commentTextEdit->clear();
       ui->commentTextEdit->setEnabled(true);
       ui->commentButton->setEnabled(true); // 启用商品评论按钮

    // 加载该商品的评论
    loadProductComments(m_currentProductId);
}

//加载所选商品评论
void commentWidget::loadProductComments(int productId)
{
    // 清空现有数据
    m_commentModel->removeRows(0, m_commentModel->rowCount());

    if (productId == -1)       return;
    // 查询商品评论
    QSqlQuery query;
    query.prepare(
        "SELECT c.comment_id, c.product_id,c.rating, c.create_time,c.content "
        "FROM Comments c "
        "WHERE c.product_id =?"
        "ORDER BY c.create_time DESC"
    );
    query.addBindValue(productId);

    if(query.exec()){
        while(query.next()){
            int commentId=query.value("comment_id").toInt();
            int commentProductId=query.value("product_id").toInt();
            int rating=query.value("rating").toInt();
            QString content=query.value("content").toString();
            QDateTime createTime=query.value("create_time").toDateTime();

            QList<QStandardItem*> row;
            row<<new QStandardItem(QString::number(commentId));
            row<<new QStandardItem(QString::number(commentProductId));
            row<<new QStandardItem(QString("%1星").arg(rating));
            row<<new QStandardItem(content.left(30) + (content.length() > 30 ? "..." : ""));
            row<<new QStandardItem(createTime.toString("yyyy-MM-dd hh:mm:ss"));


            m_commentModel->appendRow(row);
        }
    }else{
        qWarning() << "Failed to load product comments:" << query.lastError().text();
        QMessageBox::warning(this, "警告", "加载评论失败！！！");
    }
}

//对评论进行筛选
void commentWidget::filterComments()
{
    // 清空现有数据
    m_commentModel->removeRows(0, m_commentModel->rowCount());

    // 构建筛选条件
    QString whereClause = "WHERE 1=1";
    QList<QVariant> params;

    // 商品筛选
    int productId = ui->productCombo->currentData().toInt();
    if (productId != -1) {
        whereClause += " AND c.product_id = ?";
        params.append(productId);
    }

    // 评分筛选
    if (ui->rating5->isChecked()) {
        whereClause += " AND c.rating = 5";
        qDebug() << "xuanzelewuxing";
    } else if (ui->rating4->isChecked()) {
        whereClause += " AND c.rating = 4";
    } else if (ui->rating3->isChecked()) {
        whereClause += " AND c.rating = 3";
    } else if (ui->rating2->isChecked()) {
        whereClause += " AND c.rating = 2";
    } else if (ui->rating1->isChecked()) {
        whereClause += " AND c.rating = 1";
    }

    // 时间筛选
    QString dateOption = ui->DateBox->currentData().toString();
    QDate today = QDate::currentDate();

    // 根据选择的时间范围构建查询条件
    if (dateOption == "今天") {
        whereClause += " AND STRFTIME('%Y-%m-%d', c.create_time) = ?";
        QString dateStr = today.toString("yyyy-MM-dd");
        params.append(dateStr);
        qDebug() << "日期筛选: 今天 (" << dateStr << ")";
    }
    else if (dateOption == "本周") {
        QDate weekStart = today.addDays(1 - today.dayOfWeek());
                QDate weekEnd = weekStart.addDays(6);
                whereClause += " AND (STRFTIME('%Y-%m-%d', c.create_time) BETWEEN ? AND ?)";
                params.append(weekStart.toString("yyyy-MM-dd")); // 新增 2 个参数
                params.append(weekEnd.toString("yyyy-MM-dd"));
        qDebug() << "日期筛选: 本周 (" << weekStart.toString("yyyy-MM-dd") << " 至 " << weekEnd.toString("yyyy-MM-dd") << ")";
    }
    else if (dateOption == "本月") {
        QDate monthStart(today.year(), today.month(), 1);
                QDate monthEnd(today.year(), today.month(), today.daysInMonth());
                whereClause += " AND (STRFTIME('%Y-%m-%d', c.create_time) BETWEEN ? AND ?)";
                params.append(monthStart.toString("yyyy-MM-dd")); // 新增 2 个参数
                params.append(monthEnd.toString("yyyy-MM-dd"));
        qDebug() << "日期筛选: 本月 (" << monthStart.toString("yyyy-MM-dd") << " 至 " << monthEnd.toString("yyyy-MM-dd") << ")";
    }
    else if (dateOption == "全部") {
        // 全部选项不添加额外条件
        qDebug() << "日期筛选: 全部时间范围";
    }
    else {
        qDebug() << "日期筛选: 未知选项 (" << dateOption << ")";
    }

    // 查询评论
    QSqlQuery query;
    QString sql=QString(
        "SELECT c.comment_id,c.product_id, c.rating, c.content, c.create_time,c.content  "
        "FROM Comments c "
         "%1 "
        "ORDER BY c.create_time DESC"
     ).arg(whereClause);

    query.prepare(sql);
    // 绑定参数 - 使用索引方式确保正确性
    for (int i = 0; i < params.size(); ++i) {
        query.bindValue(i, params[i]);
    }

    if(query.exec()){
        while(query.next()){
            int commentId=query.value("comment_id").toInt();
            int productId=query.value("product_id").toInt();
            int rating=query.value("rating").toInt();
            QString content=query.value("content").toString();
            QDateTime createTime=query.value("create_time").toDateTime();

            QList<QStandardItem*> row;
            row<<new QStandardItem(QString::number(commentId));
            row<<new QStandardItem(QString::number(productId));
            row<<new QStandardItem(QString("%1星").arg(rating));
            row<<new QStandardItem(content.left(30) + (content.length() > 30 ? "..." : ""));
            row<<new QStandardItem(createTime.toString("yyyy-MM-dd hh:mm:ss"));

            m_commentModel->appendRow(row);
        }
    } else {
        qCritical() << "查询失败:" << query.lastError().text();
        QMessageBox::critical(this, "错误", QString("筛选评论失败:\n%1").arg(query.lastError().text()));
    }
}

 //重置筛选条件
void commentWidget::on_resetButton_clicked()
{
    // 重置筛选条件
    ui->productCombo->setCurrentIndex(0);//所有商品
    ui->ratingAll->setChecked(true);//所有评分
    ui->DateBox->setCurrentIndex(3);//默认选中“所有"

    // 清空评论详情
    ui->commentTextEdit->clear();
    ui->replyTextEdit->clear();
    ui->commentButton->setEnabled(false);
    //ui->replyButton->setEnabled(false);

    m_currentProductId=-1;
    // 重新筛选评论
    filterComments();
}

//点击评论表
void commentWidget::on_commentTable_clicked(const QModelIndex &index)
{
    if (!index.isValid()) return;

        int row = index.row();
        int commentId = m_commentModel->data(m_commentModel->index(row, 0)).toInt();

        // 查询评论及管理员回复
        QSqlQuery query;
        query.clear();
        query.prepare("SELECT c.content, c.reply  "
                      "FROM Comments c "
                      "WHERE c.comment_id = ?");
        query.addBindValue(commentId);


            qDebug() << "SQL中的占位符数量:" << query.lastQuery();
            qDebug() << "实际绑定的参数数量:" << query.boundValues().size();

        if (query.exec()&&query.next()) {
            // 1. 显示评论原文
            QString comment = query.value("content").toString();
            ui->commentLabel->setText(QString("%1").arg(comment));
            // 2. 处理管理员回复（显示在replyTextEdit）
            QString adminReply = query.value("reply").toString().trimmed();

            if (!adminReply.isEmpty()) {
                // 有管理员回复：显示内容并启用
                ui->replyTextEdit->setText(adminReply);
                ui->replyTextEdit->setEnabled(true);
            } else {
                // 无管理员回复：清空并禁用
                ui->replyTextEdit->clear();
                ui->replyTextEdit->setEnabled(false);
            }

            // 3. 启用回复输入框（commentTextEdit）和回复按钮
            ui->commentTextEdit->clear();
            ui->commentTextEdit->setEnabled(true);
            ui->commentButton->setEnabled(false); // 禁用商品评论按钮
        } else {
            //无结果或查询失败
            qWarning() << "加载评论失败11111:" << query.lastError().text();
            ui->commentLabel->clear();
            ui->commentTextEdit->clear();
            ui->replyTextEdit->clear();
            ui->commentTextEdit->setEnabled(false);
            ui->replyTextEdit->setEnabled(false);
            ui->commentButton->setEnabled(false);
        }
}
